package net.chenlin.dp.modules.business.service.impl;

import io.swagger.annotations.ApiModel;
import net.chenlin.dp.common.entity.Page;
import net.chenlin.dp.common.entity.Query;
import net.chenlin.dp.common.entity.R;
import net.chenlin.dp.common.utils.CommonUtils;
import net.chenlin.dp.modules.business.dao.LineChartMapper;
import net.chenlin.dp.modules.business.dao.TcpDataMapper;
import net.chenlin.dp.modules.business.entity.dto.TcpLineChartQueryDto;
import net.chenlin.dp.modules.business.entity.vo.deviceCalibration.CalibrationFactorVo;
import net.chenlin.dp.modules.business.entity.vo.tcp.NewDataListVo;
import net.chenlin.dp.modules.business.entity.vo.tcp.TcpDataList;
import net.chenlin.dp.modules.business.entity.vo.tcp.TcpLineChartVo;
import net.chenlin.dp.modules.business.service.TcpDataService;
import net.chenlin.dp.modules.business.service.TreeService;
import org.apache.commons.configuration.tree.TreeUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Yangsm
 * @ClassName: TcpDataServiceImpl
 * @Description: TODO
 * @date 2023年03月09日 15:32
 */
@Service
public class TcpDataServiceImpl implements TcpDataService {

    @Autowired
    private TcpDataMapper tcpDataMapper;

    @Autowired
    private TreeService treeService;

    @Autowired
    private LineChartMapper lineChartMapper;

    @Override
    public Page<TcpDataList> getTcpDataList(Map<String, Object> params) {

        // 判断
        String deviceNo = (String) params.get("deviceNo");
        if(deviceNo.contains("/")){
            deviceNo = deviceNo.substring(0,deviceNo.indexOf("/"));
            params.put("deviceNo",deviceNo);
        }

        Query query = new Query(params);
        Page<TcpDataList> page = new Page<>(query);
        List<TcpDataList> list =  tcpDataMapper.getTcpDataList(page, query);

        BigDecimal A_calibrationFactor = new BigDecimal(1.00);
        BigDecimal B_calibrationFactor = new BigDecimal(1.00);
        BigDecimal C_calibrationFactor = new BigDecimal(1.00);

        // 根据设备ID获取设备校准系数
        if(StringUtils.isNotEmpty(deviceNo)){
            List<BigDecimal> calibrationFactorList = tcpDataMapper.getCalibrationFactor(deviceNo);
            for (int i = 0; i < calibrationFactorList.size(); i++) {
                BigDecimal bigDecimal = calibrationFactorList.get(i);
                if(i == 0){
                    A_calibrationFactor = bigDecimal;
                }
                if(i == 1){
                    B_calibrationFactor = bigDecimal;
                }
                if(i == 2){
                    C_calibrationFactor = bigDecimal;
                }
            }
        }

        for (int i = 0; i < list.size(); i++) {

            // 2024/01/02 新增修改
            // APP端设备详情的ABC三相乘以校准系数
            BigDecimal a = new BigDecimal(list.get(i).getOneChannelMinutePower());
            BigDecimal b = new BigDecimal(list.get(i).getTwoChannelMinutePower());
            BigDecimal c = new BigDecimal(list.get(i).getThreeChannelMinutePower());
            BigDecimal amultiply = a.multiply(A_calibrationFactor);
            list.get(i).setOneChannelMinutePower(amultiply.toString());
            BigDecimal bmultiply = b.multiply(B_calibrationFactor);
            list.get(i).setTwoChannelMinutePower(bmultiply.toString());
            BigDecimal cmultiply = c.multiply(C_calibrationFactor);
            list.get(i).setThreeChannelMinutePower(cmultiply.toString());


//            String minutePowerTotal = list.get(i).getMinutePowerTotal();
//            double v = Double.parseDouble(minutePowerTotal);
//            DecimalFormat df = new DecimalFormat("#.00");
//            Double m = Double.valueOf(df.format(v));
//            list.get(i).setMinutePowerTotal(String.valueOf(m));
            // 2024/01/02 计算通道15分钟电量总和
            list.get(i).setMinutePowerTotal(amultiply.add(bmultiply).add(cmultiply).toString());


            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = sdf.format(list.get(i).getCreatTime());
            Double numTotal = tcpDataMapper.getAddUp(list.get(i).getDeviceNo(),format);
            // TODO: 2024/1/2 APP端设备详情的累计电能乘以校准系数
            // 2024/01/02 新增修改


            list.get(i).setAccumulatedPowerTotal(String.valueOf(numTotal));
        }
        return page;
    }

    @Override
    public R getTcpLineChart(TcpLineChartQueryDto queryDto) {
        if(StringUtils.isEmpty(queryDto.getDeviceNo())){

        }
        if(null == queryDto.getPassNo()){

        }

        List<TcpLineChartVo> list =  tcpDataMapper.getTcpLineChart(queryDto);
        return CommonUtils.msg(list);
    }

    @Override
    public Page<NewDataListVo> getNewDatalist(Map<String, Object> params) {
        Query query = new Query(params);
        Page<NewDataListVo> page = new Page<>(query);
        List<NewDataListVo> list =  tcpDataMapper.getNewDatalist(page, query);

        list.stream().forEach(newDataListVo -> {
            String deviceNo = newDataListVo.getDeviceNo();
            // “当前计量周期”如果昨天满足24小时计量周期就是昨天 如果不满足就为空
            // 判断昨天的TCP数据是否满足96条数据
            int num = tcpDataMapper.getYesTcpNum(deviceNo);
            if(num == 96){

                Calendar cal= Calendar.getInstance();
                cal.add(Calendar.DATE,-1);
                Date d=cal.getTime();
                SimpleDateFormat sp=new SimpleDateFormat("MM月-dd日");
                String yesterday = sp.format(d);//获取昨天日期
                newDataListVo.setCurrentMeasurementPeriod(yesterday+" 0时-24时");

                //Double tatal = tcpDataMapper.getTcpYesterdayTotal(deviceNo);
                //newDataListVo.setDeviceMeteredElectricity(tatal);

                // 2024/1/3  监测设备上传的电量乘以校准系数，数据库中如果有的设备没有校准系数的，就先给这些设备的校准系数赋值为1

                BigDecimal A_calibrationFactor = new BigDecimal(1.00);
                BigDecimal B_calibrationFactor = new BigDecimal(1.00);
                BigDecimal C_calibrationFactor = new BigDecimal(1.00);

                // 根据设备ID获取设备校准系数
                if(StringUtils.isNotEmpty(deviceNo)){
                    List<BigDecimal> calibrationFactorList = tcpDataMapper.getCalibrationFactor(deviceNo);
                    for (int i = 0; i < calibrationFactorList.size(); i++) {
                        BigDecimal bigDecimal = calibrationFactorList.get(i);
                        if(i == 0){
                            A_calibrationFactor = bigDecimal;
                        }
                        if(i == 1){
                            B_calibrationFactor = bigDecimal;
                        }
                        if(i == 2){
                            C_calibrationFactor = bigDecimal;
                        }
                    }
                }

                BigDecimal AphaseSequence = tcpDataMapper.getAphaseSequence(deviceNo);
                BigDecimal BphaseSequence = tcpDataMapper.getBphaseSequence(deviceNo);
                BigDecimal CphaseSequence = tcpDataMapper.getCphaseSequence(deviceNo);
                BigDecimal amultiply = AphaseSequence.multiply(A_calibrationFactor);
                BigDecimal bmultiply = BphaseSequence.multiply(B_calibrationFactor);
                BigDecimal cmultiply = CphaseSequence.multiply(C_calibrationFactor);

                newDataListVo.setDeviceMeteredElectricity(amultiply.add(bmultiply).add(cmultiply).doubleValue());

                if(newDataListVo.getDistrictId() == null){
                    SimpleDateFormat spda = new SimpleDateFormat("yyyy-MM-dd");
                    String dateTime = spda.format(d);//获取昨天日期
                    String subDeviceNo = deviceNo.substring(deviceNo.length() - 4, deviceNo.length());
                    Double onEleTotal = lineChartMapper.getDeviceEleTotalByDayAndOneDeviceNo(dateTime,subDeviceNo);
                    newDataListVo.setElectricityMeterMetering(onEleTotal);
                    return;
                }
                // 获取当前设备的子级
                Integer districtId = Math.toIntExact(newDataListVo.getDistrictId());
                List<String> allChildrenIdWithParentId = treeService.getAllChildrenIdWithParentId(deviceNo, districtId);
                List<String> newDeviceList = new ArrayList<>();
                allChildrenIdWithParentId.stream().forEach(deviceNum -> {
                    String substring = deviceNum.substring(deviceNum.length() - 4, deviceNum.length());
                    newDeviceList.add(substring);
                });

                // TODO: 2023/5/9 计算关联的电表的累计电量
                SimpleDateFormat spda = new SimpleDateFormat("yyyy-MM-dd");
                String dateTime = spda.format(d);//获取昨天日期
                //String dateTime = "2023-04-12";

                if(allChildrenIdWithParentId.size() != 1){
                    Map<String,Double> map = new HashMap<String,Double>();
                    for(String childDeviceNo: allChildrenIdWithParentId){
                        // 判断是否是最低一级
                        int count = tcpDataMapper.isFather(childDeviceNo);
                        if(count == 0){
                            String subDeviceNo = childDeviceNo.substring(childDeviceNo.length() - 4, childDeviceNo.length());
                            Double onEleTotal = lineChartMapper.getDeviceEleTotalByDayAndOneDeviceNo(dateTime,subDeviceNo);
                            if(onEleTotal == null ){
                                return;
                            }
                            String parentDeviceNo = tcpDataMapper.getParentDeviveNo(childDeviceNo);
                            Double aDouble = map.get(parentDeviceNo);
                            if(aDouble == null && StringUtils.isNotEmpty(parentDeviceNo)){
                                map.put(parentDeviceNo,onEleTotal);
                            }
                            if(aDouble != null && StringUtils.isNotEmpty(parentDeviceNo)){
                                BigDecimal c1 = new BigDecimal(Double.toString(onEleTotal));
                                BigDecimal c2 = new BigDecimal(Double.toString(aDouble));
                                aDouble = c1.add(c2).doubleValue();
                                map.put(parentDeviceNo,aDouble);
                            }
                        }
                    }
                    // 递归累计数据
                    Map<String, Double> stringDoubleMap = treeService.toParentMap(map, deviceNo);
                    Double electricityMeterMetering = stringDoubleMap.get(newDataListVo.getDeviceNo());
                    newDataListVo.setElectricityMeterMetering(electricityMeterMetering);
                }else{
                    String substring = deviceNo.substring(deviceNo.length() - 4, deviceNo.length());
                    Double excelTatal = tcpDataMapper.getExcelImportData(substring,dateTime);
                    newDataListVo.setElectricityMeterMetering(excelTatal);
                }
            }
        });
        return page;
    }
}
